<!--数据查询  -->
<template>
  <div class="">
    <el-card>
      <el-form ref="FtuForm" :model="formData" label-width="70px" size="mini">
        <el-row :class="isForm ? 'show' : 'hide'">
          <el-col :span="6">
            <el-form-item label="网关名称" prop="gw_sn">
              <el-select
                style="width: 100%"
                v-model="formData.gw_sn"
                placeholder="请选择"
                clearable
                @change="GWselectChange"
              >
                <el-option
                  v-for="(item, index) in GwList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="终端名称" prop="term_key">
              <el-select
                style="width: 100%"
                v-model="formData.term_key"
                placeholder="请选择"
                clearable
                @change="ZDselectChange"
              >
                <el-option
                  v-for="(item, index) in ZdList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="数据类型" prop="from">
              <el-select
                style="width: 100%"
                v-model="formData.from"
                placeholder="请选择"
                @change="selectChange"
                clearable
              >
                <el-option label="遥信" value="data-yx"></el-option>
                <el-option label="遥测" value="data-yc"></el-option>
                <el-option label="遥脉" value="data-ym"></el-option>
                <el-option label="定时任务" value="data-task"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数据id" prop="id">
              <el-select
                style="width: 100%"
                v-model="formData.id"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in dataIdList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <span class="ColisShow" @click="OnFromclick">{{
              isForm ? "收起" : "展开"
            }}</span>
          </el-col>
          <div v-show="isForm">
            <el-col :span="6">
              <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker
                  style="width: 100%"
                  v-model="formData.beginTime"
                  type="datetime"
                  range-separator=":"
                  placeholder="选择开始日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  style="width: 100%"
                  v-model="formData.endTime"
                  type="datetime"
                  range-separator=":"
                  placeholder="选择结束日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <div style="margin-left: 15px">
                <el-button size="mini" type="primary" @click="query"
                  >查询</el-button
                >
                <el-button size="mini" type="danger" @click="resset"
                  >重置</el-button
                >
                <el-button type="primary" size="mini" @click="exportButton"
                  >导出</el-button
                >
              </div>
            </el-col>
          </div>
        </el-row>
      </el-form>
    </el-card>
    <!-- <el-card style="margin-top: 20px">
      
    </el-card> -->
    <el-tabs
      type="border-card"
      style="margin-top: 5px"
      @tab-click="handleClick"
    >
      <el-tab-pane label="报表展示">
        <yg-table
          id="myTable"
          :columns="columns"
          :tableList="TableList"
          :loading="Tableloading"
        ></yg-table>
        <div style="margin-top: 10px" v-show="TableList.length > 0">
          <b>共 {{ TableList.length }} 条</b>
        </div>
      </el-tab-pane>
      <el-tab-pane label="图形展示">
        <div v-if="myChartShow">
          <div id="line" style="height: 570px; width: 100%" ref="myChart"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { myStorage } from "@/utils/localStorage";
import YgTable from "@/components/Table/YgTable.vue";
import { exportExcel } from "@/utils/exportExcelBlob/index";
import {
  setMessageCallback,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";

export default {
  //import引入的组件需要注入到对象中才能使用
  name: "DataQuery",
  components: {
    YgTable,
  },
  data() {
    //这里存放数据
    return {
      columns: [
        {
          prop: "datetime",
          label: "更新时间",
        },
        {
          prop: "value",
          label: "值/(单位)",
        },
      ],
      TableList: [],
      formData: {
        gw_sn: "",
        term_key: "",
        from: "",
        id: "",
        beginTime: "",
        endTime: "",
      },
      myChart: null,
      myChartX: [],
      myChartY: [],
      title: "",
      myChartName: "",
      myChartShow: false,
      dataIdList: [],
      yxList: [],
      ycList: [],
      ymList: [],
      taskList: [],
      GwList: [],
      ZdList: [],
      Tableloading: false,
      isForm: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    TableList: {
      deep: true,
      handler: function (val, oldval) {
        //console.log(val, oldval);
        if (val.length > 0) {
          this.$nextTick(() => {
            this.renderMychart();
          });
        }
      },
    },
  },
  //方法集合
  methods: {
    query() {
      this.TableList = [];
      // this.dataIdList = []
      this.myChartX = [];
      this.myChartY = [];
      let newMsg = {
        webMsgType: 1020,
        funCode: 0,
      };

      newMsg.data = this.formData;
      publishMsg(newMsg);
      this.Tableloading = true;
    },
    resset() {
      this.$refs.FtuForm.resetFields();
    },
    exportButton() {
      if (this.TableList.length == 0) {
        this.$message.warning("请查询数据后再导出！");
      } else {
        exportExcel(document.getElementById("myTable"), `数据报表.xlsx`);
      }
    },
    OnFromclick() {
      this.isForm = !this.isForm;
      console.log(this.isForm);
    },
    handleClick(tab) {
      // //console.log(tab)
      if (tab.index === "0") {
        this.myChartShow = false;
      }
      if (tab.index === "1") {
        this.myChartShow = true;
        setTimeout(() => {
          this.renderMychart();
        }, 100);
      }
    },
    selectChange(val) {
      //console.log(val);
      this.dataIdList.splice(0, this.dataIdList.length);
      switch (val) {
        case "data-yx":
          let newMsgyx = {
            webMsgType: 1009,
            funCode: 0,
          };
          newMsgyx.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgyx);
          this.formData.id = "";
          this.dataIdList = this.yxList;
          break;
        case "data-yc":
          let newMsgyc = {
            webMsgType: 1010,
            funCode: 0,
          };
          newMsgyc.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgyc);
          this.formData.id = "";
          this.dataIdList = this.ycList;
          break;
        case "data-ym":
          let newMsgym = {
            webMsgType: 1011,
            funCode: 0,
          };
          newMsgym.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgym);
          this.formData.id = "";
          this.dataIdList = this.ymList;
          break;
        case "data-task":
          let newMsgtask = {
            webMsgType: 1015,
            funCode: 0,
          };
          newMsgtask.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgtask);
          this.formData.id = "";
          this.dataIdList = this.taskList;
          break;
        default:
          break;
      }
    },
    GWselectChange(val) {
      this.formData.term_key = "";
      this.formData.id = "";
      this.formData.from = "";
      this.dataIdList.splice(0, this.dataIdList.length);
      publishMsg({
        webMsgType: 1008, //发送请求终端消息
        funCode: 0,
        data: { gw_sn: val },
      });
    },
    ZDselectChange(val) {
      this.dataIdList.splice(0, this.dataIdList.length);
      this.formData.from = "";
      this.formData.id = "";
      // console.log(val, "终端点击");
    },
    renderMychart() {
      if (
        this.myChart != null &&
        this.myChart != "" &&
        this.myChart != undefined
      ) {
        this.myChart.dispose(); //销毁
      }
      this.myChart = this.$echarts.init(this.$refs.myChart);
      var options = {
        tooltip: {
          trigger: "axis",
        },
        title: {
          text: `${this.myChartName}曲线图`,
          left: "center",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.myChartX,
        },
        yAxis: {
          type: "value",
          name: this.title,
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
          },
        },
        series: [
          {
            name: this.title,
            data: this.myChartY,
            type: "line",
          },
        ],
      };
      this.myChart.setOption(options, true);
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
    onMessage(topic, msg) {
      //console.log("正在监听--终端页面数据", topic, msg);
      switch (msg.webMsgType) {
        case 1020:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  this.title = msg.data.unit;
                  this.myChartName = msg.data.name;
                  if (msg.data.data) {
                    this.TableList = msg.data.data;
                    this.TableList.forEach((e) => {
                      this.myChartX.push(e.datetime);
                      this.myChartY.push(e.value);
                    });
                  } else {
                    this.$message.error("获取数据列表失败");
                  }
                  this.Tableloading = false;
                }
              }
              break;
            default:
              break;
          }
          break;
        case 1007:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                msg.data.map((e) => {
                  return this.GwList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
                break;
              }
          }
          break;
        case 1008:
          if (checkSpecialId(msg)) {
            switch (msg.funCode) {
              case 0:
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                this.ZdList = [];
                let list = [{ name: "全选", id: "all" }];
                msg.data.forEach((e) => {
                  list.push({
                    name: e.name,
                    id: e.id,
                  });
                });
                this.ZdList = list;
                break;
              default:
                break;
            }
          }
          break;
        case 1009:
          switch (msg.funCode) {
            case 0:
              if (msg.retCode != 0 || !msg.data) {
                return this.$message.error(msg.retMsg);
              }
              let res = msg.data;
              res.map((e) => {
                return this.yxList.push({
                  name: e.name,
                  id: e.id,
                });
              });
              break;
            default:
              break;
          }
          break;
        case 1010:
          switch (msg.funCode) {
            case 0:
              if (msg.retCode != 0 || !msg.data) {
                return this.$message.error(msg.retMsg);
              }
              let res = msg.data;
              res.map((e) => {
                return this.ycList.push({
                  name: e.name,
                  id: e.id,
                });
              });
              break;
            default:
              break;
          }
          break;
        case 1011:
          switch (msg.funCode) {
            case 0:
              if (msg.retCode != 0 || !msg.data) {
                return this.$message.error(msg.retMsg);
              }
              let res = msg.data;
              res.map((e) => {
                return this.ymList.push({
                  name: e.name,
                  id: e.id,
                });
              });
              break;
            default:
              break;
          }
          break;
        case 1015:
          switch (msg.funCode) {
            case 0:
              if (msg.retCode != 0 || !msg.data) {
                return this.$message.error(msg.retMsg);
              }
              let res = msg.data;
              res.map((e) => {
                return this.taskList.push({
                  name: e.name,
                  id: e.id,
                });
              });
              break;
            default:
              break;
          }
          break;

        default:
          break;
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.options = this.value;
    setMessageCallback(this.onMessage);
    publishMsg({
      webMsgType: 1007, //发送网关消息
      funCode: 0,
    });
  },
  destroyed() {
    removeMessageCallback(this.onMessage);
    window.removeEventListener("resize", () => {
      this.myChart.resize();
    });
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 5px 5px 5px 5px;
}

.show {
  height: 60px;
  // transition: 0.2s;
}
.hide {
  height: 30px;
  // transition: 0.2s;
}
.ColisShow {
  display: block;
  text-align: center;
  line-height: 30px;
  font-weight: 600;
  font-size: 12px;
  color: red;
  cursor: pointer;
}
</style>
